package com.hs.config;

import com.hs.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        if (user != null) {
            return true;
        } else {
            // response.sendRedirect("login"); 重定向要用绝对路径，不加斜杠是相对路径，所以每次重定向都会将"login"添加到本次请求url的后面，下一次请求还是会被拦下来
            response.sendRedirect("/login"); // 将"login"改为"/login",在前面加"/",这样就变成了绝对路径，每次重定向的时候就能正确访问了
            return false;
        }
    }

}
